from fastapi import Request
import hashlib
import re

def get_browser_type(user_agent: str) -> str:
    """识别浏览器类型"""
    user_agent = user_agent.lower()
    if "edg" in user_agent:
        return "Edge"
    elif "chrome" in user_agent and "chromium" not in user_agent:
        return "Chrome"
    elif "firefox" in user_agent:
        return "Firefox"
    elif "safari" in user_agent and "chrome" not in user_agent:
        return "Safari"
    elif "opera" in user_agent or "opr" in user_agent:
        return "Opera"
    else:
        return "Browser"

def get_device_type(user_agent: str) -> str:
    """根据 User-Agent 判断设备类型"""
    user_agent = user_agent.lower()
    
    # 检查是否是移动设备
    if "android" in user_agent:
        return "Android"
    elif "iphone" in user_agent or "ipad" in user_agent or "ios" in user_agent:
        return "iOS"
    
    # 检查是否是桌面操作系统
    if "windows" in user_agent:
        if "mobile" in user_agent:
            return "Windows_Mobile"
        return "Windows"
    elif "macintosh" in user_agent or "mac os" in user_agent:
        return "macOS"
    elif "linux" in user_agent:
        if "android" not in user_agent:
            return "Linux"
        return "Android"
    
    # 如果是通过 Web 浏览器访问
    if any(browser in user_agent for browser in ["chrome", "firefox", "safari", "edg", "opera", "opr"]):
        return f"Web_{get_browser_type(user_agent)}"
    
    return "Unknown"

def get_device_id(request: Request) -> str:
    """
    从请求中获取设备标识
    优先使用请求头中的 X-Device-ID，如果没有则根据 User-Agent 生成
    返回格式：设备类型_设备哈希值，例如：Windows_abc123, Web_Chrome_abc123
    """
    # 尝试从请求头获取设备 ID
    device_id = request.headers.get("X-Device-ID")
    if device_id:
        # 如果客户端提供了设备 ID，确保它包含设备类型前缀
        if "_" not in device_id:
            user_agent = request.headers.get("User-Agent", "unknown")
            device_type = get_device_type(user_agent)
            return f"{device_type}_{device_id}"
        return device_id

    # 如果没有设备 ID，使用 User-Agent 和 IP 地址生成
    user_agent = request.headers.get("User-Agent", "unknown")
    client_host = request.client.host if request.client else "unknown"
    
    # 获取设备类型
    device_type = get_device_type(user_agent)
    
    # 生成设备哈希
    device_info = f"{user_agent}:{client_host}"
    device_hash = hashlib.md5(device_info.encode()).hexdigest()[:8]
    
    return f"{device_type}_{device_hash}" 